package socket2;

import io.ReadDemo;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Scanner;

public class Cient {
    private Socket socket;

    public Cient() {
            try {
                System.out.println("正在与服务端建立连接");
                //与服务端建立连接，确定服务端的ip和端口号
                socket = new Socket("localhost", 8088);
                System.out.println("已经与服务端建立连接");
                start();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    public void start(){
        Thread t1  = new Thread(){
            public void run() {
                while (true) {
                    try {
                        InputStream is = socket.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                        BufferedReader br = new BufferedReader(isr);
                        String a;
                        if ((a = br.readLine()) != null) {
                            System.out.println(a);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        t1.setDaemon(true);
        t1.start();
        try {
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(
            new BufferedWriter(
            new OutputStreamWriter(os, StandardCharsets.UTF_8)),true);

            Scanner scanner = new Scanner(System.in);

            while (true) {
                String a = scanner.nextLine();
                if ("exit".equalsIgnoreCase(a)){
                    break;
                }
                pw.println(a);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new Cient();
    }
}
